package connect;

import BDD.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.helpers.AttributesImpl;

import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/gamebook")
public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */

	Connection connection;
	PrintWriter out;
	Transformer transfo;
	Transformer transfo2;
	ByteArrayOutputStream buff;
	TransformerHandler handler;
	StreamResult res;

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);

		try {
			connection = ConfigConnection.getConnection("connexion.properties");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	public void connectify(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			System.out.println(request.getSession(true).getAttribute("equipe"));
			// out.println(request.getSession().getAttribute("role"));
			// else
			// out.println("guest");

			response.setContentType("text/html");
			out = response.getWriter();
			buff = new ByteArrayOutputStream();
			res = new StreamResult(out);
			Statement pStatement = connection.createStatement();
			String query = "";
			if(request.getSession(true).getAttribute("role").equals("restricted")){
				query ="SELECT * FROM user LEFT JOIN equipe ON user.Joueur_Equipe = equipe.Equipe_ID WHERE user.Joueur_Equipe =";
				query += request.getSession(true).getAttribute("equipe") ;
				//query += "AND (Joueur_Equipe = Partie_Eq1_ID OR Partie_Eq2_ID)";
			//}else if (request.getParameter("equipe") != null){
				//query = "SELECT * FROM user LEFT JOIN equipe ON user.Joueur_Equipe = equipe.Equipe_ID WHERE equipe.Equipe_ID= ";
				//query += request.getParameter("equipe");
				
			}else{
				query = "SELECT * FROM user LEFT JOIN equipe ON user.Joueur_Equipe = equipe.Equipe_ID";
				//query = "SELECT * FROM user, equipe, partie WHERE Joueur_Equipe = Equipe_ID AND (Joueur_Equipe = Partie_Eq1_ID OR Partie_Eq2_ID) ";

			}
			ResultSet rSet = pStatement.executeQuery(query);
			AttributesImpl atts = new AttributesImpl();
			SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
			handler = factory.newTransformerHandler();
			transfo = handler.getTransformer();

			Templates templates = factory.newTemplates(new StreamSource( new File(getServletContext().getRealPath("WEB-INF") + "/template.xsl")));
			TransformerHandler handler = factory.newTransformerHandler(templates);
			handler.setResult(res);
			handler.startDocument();
			atts.addAttribute("", "role", "role", "",request.getSession(true).getAttribute("role").toString());
			handler.startElement("", "Joueurs", "Joueurs", atts);
			atts.clear();

			while (rSet.next()) {
				atts.addAttribute("", "id", "id", "",rSet.getString("Joueur_ID"));
				handler.startElement("", "Joueur", "Joueur", atts);
				atts.clear();

				handler.startElement("", "pseudo", "pseudo", atts);

				String pseudo = rSet.getString("Joueur_Pseudo");
				handler.characters(pseudo.toCharArray(), 0, pseudo.length());
				handler.endElement("", "pseudo", "pseudo");

				handler.startElement("", "age", "age", atts);
				String age = String.valueOf(rSet.getInt("Joueur_Age"));
				handler.characters(age.toCharArray(), 0, age.length());
				handler.endElement("", "age", "age");

				/*
				 * handler.startElement("", "pass", "pass", atts); String Pwd =
				 * rSet.getString("Joueur_Pwd");
				 * handler.characters(Pwd.toCharArray(), 0 , Pwd.length());
				 * handler.endElement("" ,"pass","pass");
				 */

				handler.startElement("", "sex", "sex", atts);
				String sex = rSet.getString("Joueur_Sex");
				handler.characters(sex.toCharArray(), 0, sex.length());
				handler.endElement("", "sex", "sex");

				handler.startElement("", "mail", "mail", atts);
				String Mail = rSet.getString("Joueur_Mail");
				handler.characters(Mail.toCharArray(), 0, Mail.length());
				handler.endElement("", "mail", "mail");

				handler.startElement("", "description", "description", atts);
				String descr = rSet.getString("Joueur_Descirption");
				handler.characters(descr.toCharArray(), 0, descr.length());
				handler.endElement("", "description", "description");

				atts.addAttribute("", "equipe_id", "equipe_id","", rSet.getString("user.Joueur_Equipe"));
				handler.startElement("", "equipe", "equipe", atts);
				String equipe = rSet.getString("Equipe_nom");
				handler.characters(equipe.toCharArray(), 0, equipe.length());
				handler.endElement("", "equipe", "equipe");

				handler.startElement("", "photo", "photo", atts);
				String photo = rSet.getString("Joueur_Pict");
				handler.characters(photo.toCharArray(), 0, photo.length());
				handler.endElement("", "photo", "photo");

				handler.endElement("", "Joueur", "Joueur");

			}
			handler.endElement("", "Joueurs", "Joueurs");
			/*
			 * rSet.close(); pStatement.close();
			 */
			handler.endDocument();
			out.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.println("<h1>:'s </h1>");
		}
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		ServletContext webApp = this.getServletContext();
		try {
			transfo.transform(new StreamSource(res.toString()),new StreamResult(out));

			// Forward to the JSP
			// request.setAttribute( HTML_RESULT, htmlStreamResult );
			// webApp.getRequestDispatcher( "/zoo.jsp" ).forward( request,
			// response );

		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		init();
		connectify(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		init();
		connectify(request, response);
	}

}
